dim(S)
nrow(S) # Number of rows in S
ncol(S) # Number of columns S
mode(S)
dim(v.matrix)
nrow(v.matrix)
ncol(v.matrix)
mode(v.matrix)
# As we have seen for vectors, there are operations on matrices
# Try to consult the help about the functions "t ()", "solve ()", "det ()"
# Also write "%*%" next to the magnifying glass in order to consult the
# product between matrices
S
t(S) # Transposed matrix of S
solve(S) # Inverse matrix of S: it is not full rank matrix, hence it is not invetrible
solve(A)
A #  3 X 3 matrix
v2 #  3 X 1 vectore
solve(A,v2) # "solve" is a function which solves the system A %*% x = v2
#Check:
det(A)
N=matrix(c(v2,4,11,55,23,8,1),nrow = 3); N
det(N)
x1=det(N)/det(A); x1 # Cramer's rule
# If we insert only one matrix as argument of "solve", it calculates the inverse
J=matrix(1:4, nrow = 2)
det(J) # calculate the determinant
solve(J) #calculate the inverse 2 X 2
########
A%*%S # product between matrices (row by column); it turns out to be a  3 X 3 matrix
# Select elements within arrays
# For example, we want to extract the element of place (1,1) from the matrix S
S[1,1]
# Or the element of place (2,3)
S[2,3]
# Wanting to extract the entire second row
S[2,]
# Or the whole third column
S[,3]
# Or even the first two lines
S[1:2,]
# The same result is obtained by excluding the third row
S[-3,]
# Obviously arrays can contain characters or logical elements,
# but cannot contain other variables (i.e. arrays can contain
# alphanumeric, logical or numeric characters only)
###### FREESTYLE EXAMPLE #####
P<-matrix(sample(x=1:1000, size=16, replace = FALSE), nrow=4, ncol=4 )
sample(x=1:4, size=6, replace = TRUE)
# Data frame  -------------------------------------------------------------
#Let's get back all the information about our 4 students
data=data.frame(heights,employment,year,regular)
data
# If we had observed a lot of students it wouldn't have been comfortable to visualize
# all of the data.frame, but we could have checked its specs with a command:
str(data)
mode(data)
# Note that height is a numeric variable, employment is a factor vector (vector of characters),
# year is a numeric variable, while regular is logical: TRUE or FALSE
# We cannot create a data.frame with different lengths
increasing<-1:10
length(increasing)
length(heights)
df=data.frame(increasing,heights)
mat<-cbind(increasing,heights)
# For data frames applies the same selections commands as for matrices
# Second student height: second row, first column
data[2,1]
# All data of the third student: third line
data[3,]
#Employments: second column
data[,2]
# To extrapolate the variables I can use a second strategy
# Let's look at the variable names first:
names(data)
# We us the $ operator
data$heights
# By doing so, I extract only the data referring to the height: first column
# R studio has a facility: pressing the "tab" command after writing, eg
# example, given $ we will have suggestions about the various variables
# Now let's load data from the outside.
# Pay attention to the working directory (wd) we are in
getwd()
# We may change the wd: Session>>>Set working Directory>>> Choose dierectory
#Example: setwd("~/Desktop/Lectures/Statistical Learning/")
#International format: "," is the separator and  "." is the decimal
data1 <- read.csv("csv_int.csv",header=T,dec=".",sep=",")
#International format: ";" is the separator and  "," is the decimal
data2 <- read.csv("csv_ita.csv",header=T,dec=",",sep=";")
# Lists -------------------------------------------------------------------
list.ex=list(c(1,4,5), matrix(1:9,nrow=3), "House", data)
list.ex
# We assign names to the elements:
names(list.ex)=c("vec","matrix","char","dataframe")
list.ex
# Or directly via the list command:
list.ex2=list(vec=c(1,4,5),matrix=matrix(1:9,nrow=3),char="Casa",dataframe=data)
# To select elements from a list use the "[[]]"
# We select the matrix which in this case is the second element:
list.ex[[2]]
# Or by $ operator
list.ex$matrix
# Obviously it is also possible to extract elements of elements,
# by combining the syntax of the list with that of the other objects
# where [] are always used
# We take the heights (first column) of the dataframe, which in turn is
# the fourth item in the list:
list.ex[[4]][,1]
# Or
list.ex$dataframe$heights
A<-matrix(1:9,2,2)
A<-matrix(1:16,4,4)
A
A[3,-3:4]
A[3,-(3:4)]
getwd()
setwd("~/Desktop/Lab 1")
data1 <- read.csv("csv_int.csv",header=T,dec=".",sep=",")
data2 <- read.csv("csv_ita.csv",header=T,dec=",",sep=";")
data1
str(data1)
names(data1)
names(data1)<-c("individual", "weight", "height", "age", "gender")
data1
data1 <- read.csv("csv_int.csv",header=T,dec=".",sep=",")
names(data1)
names(data1)<-c("individual", "weight", "height", "age", "gender")
str(data1)
names(data1)<-c("individual", "height", "weight", "age", "gender")
str(data1)
hist(data$heights)
par(mar=c(1,1,1,1))
hist(data$heights)
plot(density(data$heights))
head(data)
names(data1)<-c("individual", "height", "weight", "age", "gender")
data1
setwd("~/Desktop/Lectures/2023-2024/Statistical Tools/R practice/Lab 1")
data1 <- read.csv("csv_int.csv",header=T,dec=".",sep=",")
setwd("~/Desktop/Lectures/2023-2024/Statistical Tools/R practice/Lab 1")
data1 <- read.csv("csv_int.csv",header=T,dec=".",sep=",")
data2 <- read.csv("csv_ita.csv",header=T,dec=",",sep=";")
data1
list.ex=list(c(1,4,5), matrix(1:9,nrow=3), "House", data1)
list.ex
list.ex=list(c(1,4,5), matrix(1:9,nrow=3), "House", data1)
list.ex
length(list.ex)
###############################################################
### Statistical Tools for decision Making: Intoduction to R ###
######### Rosario Barone                              #########
######### email: rosario.barone@uniroma2.it           #########
###############################################################
# The symbol"#" allows to "comment" our code
c<-100-80
c
# R may be used as a calculator
2+2
4*13
(8-4)/4
6^2
# Operazions with basic functions
# Square root
sqrt(16)
(16)^(1/2)
# Absolute Value
abs(-10)
# Logarithm with base e
log(10)
# Logarithm with base 10:
log10(10)
# More complex functions need more parameters
#For example, if we want to calculate the logarithm to a base
#different from "e" and "10" we can still use the logarithm function.
#We call the help of the log function to understand the syntax to use:
?log
help(log)
log(8,2)
log(x=8, base = 2)
log(2,8)
log(base=2,x=8)
# Assignment ------------------------------------------------------------
# Directly assign values to a variable
a <- 8
a
# Or
a = 8
8 -> a
a
# BE CAREFUL: do not overwrite existing variables!
a=6
a
# Assign values that are the result of math operations
SUM = 1 + 2
SUM
OPERATION = 4 + sqrt(36)
OPERATION
# More operations can be written on the same line, just separate them with a semicolon
OPERATION2 = 7 + log(4, base=2) ;  OPERATION2
#Operations with objects:
OPERATION=SUM+OPERATION
SUM
OPERATION
# Scalar (Numeric {[Integer, Real] or Complex})
weight <- 79
weight
height <- 1.89
height
# For complex numbers there aren't real examples
imm <- 3.51+1.2i
imm
#Characters
civilstatus <- 'Single'
civilstatus
employment <- "Worker"
employment
#Logical
female <- TRUE
male <- FALSE
car.owner<- F
house.owner <- T
# For getting (or setting) the type or storage mode of an object.
mode(civilstatus)
mode(weight)
mode(imm)
mode(car.owner)
# Also
is.numeric(weight)
is.numeric(civilstatus)
is.character(civilstatus)
is.logical(female)
# Set the type of an object
weight.char=as.character(weight)
weight.char
mode(weight.char)
civilstatus.num=as.numeric(civilstatus)
civilstatus.logical=as.logical(civilstatus)
civilstatus.logical
# We cannot transform a character into a number, nor into a Boolean (logical) variable!
female.num=as.numeric(female)
female.num
mode(female.num)
male.num=as.numeric(male)
male.num
mode(male.num)
# Instead, we can transform a logical variable into a number!
weight.logical=as.logical(weight)
weight.logical
# Restituisce sempre TRUE tranne che per 0!
as.logical(0)
# Workspace: container where all the objects we created are located --------------
# We can see the variables created in the window above
# on the right, or, alternatively, we can ask
# a R to list the entire workspace using the command:
ls()
# To remove an object from the Workspace just use the rm () command
rm(a)
#To remove the "OPERATION" and "SUM" variables jointly
rm(OPERATION,SUM)
# To remove all workspace
rm (list = ls ())
# We can save the workspace or load an existing one
# using the environment panel
# New items ----------------------------------------------- ----------
# Vectors
# Let's see how to put different information in one object
# Let's assume we asked 4 people for heights
heights=c(1.87, 1.75, 1.68, 1.9)
heights
char.vec<-c("A","B","D","C")
sort(char.vec)
# If we want to sort them in increasing order
sort(heights)
# Or in decreasing orther
sort(heights, decreasing=T)
sort(heights, decreasing=TRUE)
# Attention! There is another function that returns the order of positions rather than values
order(heights)
# Obviously this also applies in descending order
order(heights, decreasing=T)
# Replicate the same value
GG2<-rep(2,times=100)
GG3<-rep(3,times=20)
ST<-c(GG2,GG3)
year=rep(2,times=100)
year=rep(3,length.out=100)
yy<-c(2,3,4)
out<-rep(yy,times=100)
out<-rep(yy,length.out=100)
year
?rep
# In the help we can see the different syntax of the "rep" function
# The "rep" function can also replicate a vector
# It is possible to achieve the same result in two different ways
vector=c(3,4,6,2)
vector.rep1=rep(vector,times=4)
vector.rep1
# Or
vector.rep2=rep(vector, length.out=15)
vector.rep2
# Sequences of integers
1:10
10:1
# Assign a name to the sequence
increasing=1:10; increasing
decreasing=10:1; decreasing
# Sequence of even numbers
help(seq)
even=seq(from=0,to=100,by=2)
even
seq(0,100,2)
# Note that "seq()" is a function which requires 3 parameters:
# from: starting number
# to: arrival number
# by: length of the step
# Parameters of a function can be specified or
# implied, in the latter case it is essential to respect the order
# By specifying the parameters, the order of the parameters becomes irrelevant
seq(to=100,by=2,from=0)
seq(by=2,from=0,to=100)
seq(to=100,from=0,by=2)
seq(from=100,to=0,by=2)
# Error! To obtain this sequence in descending order
# we need a negative step, namely -2
seq(100,0,by=-2)
# Vectors can also contain characters and logical elements
employment<-c("Student","Construction","Office","Freelance")
employment
regular<-c(TRUE,FALSE,TRUE,TRUE)  # If TRUE the student has attended all the exams of the previous years
regular
# Attention! Do not combine different variables
error1=c("Studente",TRUE,20)
error1
error2=c(0,10,TRUE,FALSE)
error2
# Operations on the vectors ###########################################################
# Length
length(heights)
# For example it can be useful if we want to find out how many there are
# multiples of a number in a range
multipliples3=seq(3,100,3)
multipliples3
length(multipliples3)
# Other useful operations:
sum(heights)
prod(heights)
diff(heights)
diff(multipliples3)
length(diff(multipliples3)) # We lose one observation
min(multipliples3)
max(multipliples3)
# Multiplication of a vector by a scalar:
# for example, let's transform heights from meters to centimeters:
heights*100
# Operations between different vectors
e=c(4,7,6,9,2); e
v=c(1,2,5,2,3); v
f=e+v
f
# Product between two vectors
p=e*v
p
# Scalar product of vectors
ps=e%*%v
ps
# If we sum the elements of the vector "p" we get the same result
sum(p)
# Note that if the operation between two vectors is not mathematically feasible
# (because, for example, the two vectors have different lengths)
# R still does the computation by "recycling" the elements
# missing. However, R reports the problem to us via a warning message
v2=c(3,2,5)
f2=e+v2
f2
#that is the same as:
v2.rep<-rep(v2, length.out=length(e))
f2.proof<-e+v2.rep
f2==f2.proof
# Select elements from a vector ----------------------
# For example, we want to know how tall the fourth student is
heights[4]
# How tall are the first 2 observed individuals?
heights[1:2]
# How tall are the first and the fourth observed individuals?
heights[c(1,4)]
# If we want to exclude the third student
heights[-3]
# Let us suppose instead we want to know how tall the shortest student is
sort.heights<-sort(heights)
sort.heights[length(sort.heights)]
# analogously:
sort(heights)[1]
# Or
sort(heights, decreasing=T)[4]
# How tall are the the two less high individuals?
sort(heights)[1:2]
# How tall are the lowest and highest?
sort(heights)[c(1,4)]
# Examples of index vectors are also logical vectors. Let's say
I=heights<1.8
# In doing so we have created a sequence of TRUE and FALSE logical elements
I
# We can extrapolate the elements that correspond to our selection criterion
heights[I]
# We can likewise exclude irrelevant elements, but the following command
# assumes knowledge of the elements to exclude
heights[c(-1,-4)]
# Matrices ###################################################################
# To create a matrix starting from vectors you can join two or more vectors
# using the "cbind ()" and "rbind ()" functions
vector1=c(12,29,26,19,15)
vector2=c(32,12,24,11,53)
v.matrix=cbind(vector1,vector2)
h.matrix=rbind(vector1,vector2)
v.matrix
h.matrix
# Or you can create a matrix directly in the following way:
S<-matrix(1:9,nrow=3,ncol=3)
S
A=matrix(c(2,3,5,4,11,55,23,8,1),nrow=3,ncol=3)
A
A=matrix(c(2,3,5,4,11,55,23,8,1),nrow=3,ncol=3, byrow = TRUE)
# To know the size (dimension) of a matrix just use "dim ()"
dim(S)
nrow(S) # Number of rows in S
ncol(S) # Number of columns S
mode(S)
dim(v.matrix)
nrow(v.matrix)
ncol(v.matrix)
mode(v.matrix)
# As we have seen for vectors, there are operations on matrices
# Try to consult the help about the functions "t ()", "solve ()", "det ()"
# Also write "%*%" next to the magnifying glass in order to consult the
# product between matrices
S
t(S) # Transposed matrix of S
solve(S) # Inverse matrix of S: it is not full rank matrix, hence it is not invetrible
solve(A)
A #  3 X 3 matrix
v2 #  3 X 1 vectore
solve(A,v2) # "solve" is a function which solves the system A %*% x = v2
#Check:
det(A)
N=matrix(c(v2,4,11,55,23,8,1),nrow = 3); N
det(N)
x1=det(N)/det(A); x1 # Cramer's rule
# If we insert only one matrix as argument of "solve", it calculates the inverse
J=matrix(1:4, nrow = 2)
det(J) # calculate the determinant
solve(J) #calculate the inverse 2 X 2
########
A%*%S # product between matrices (row by column); it turns out to be a  3 X 3 matrix
# Select elements within arrays
# For example, we want to extract the element of place (1,1) from the matrix S
S[1,1]
# Or the element of place (2,3)
S[2,3]
# Wanting to extract the entire second row
S[2,]
# Or the whole third column
S[,3]
# Or even the first two lines
S[1:2,]
# The same result is obtained by excluding the third row
S[-3,]
# Obviously arrays can contain characters or logical elements,
# but cannot contain other variables (i.e. arrays can contain
# alphanumeric, logical or numeric characters only)
# Data frame  -------------------------------------------------------------
#Let's get back all the information about our 4 students
data=data.frame(heights,employment,year,regular)
data
# If we had observed a lot of students it wouldn't have been comfortable to visualize
# all of the data.frame, but we could have checked its specs with a command:
str(data)
mode(data)
# Note that height is a numeric variable, employment is a factor vector (vector of characters),
# year is a numeric variable, while regular is logical: TRUE or FALSE
# We cannot create a data.frame with different lengths
increasing<-1:10
length(increasing)
length(heights)
df=data.frame(increasing,heights)
# For data frames applies the same selections commands as for matrices
# Second student height: second row, first column
data[2,1]
# All data of the third student: third line
data[3,]
#Employments: second column
data[,2]
# To extrapolate the variables I can use a second strategy
# Let's look at the variable names first:
names(data)
# We us the $ operator
data$heights
# By doing so, I extract only the data referring to the height: first column
# R studio has a facility: pressing the "tab" command after writing, eg
# example, given $ we will have suggestions about the various variables
data
list.ex=list(c(1,4,5), matrix(1:9,nrow=3), "House", data)
list.ex
setwd("~/Desktop/Lectures/2023-2024/Statistical Tools/R practice/Lab 1")
data1 <- read.csv("csv_int.csv",header=T,dec=".",sep=",")
list.ex=list(c(1,4,5), matrix(1:9,nrow=3), "House", data1)
list.ex
names(list.ex)=c("vec","matrix","char","dataframe")
list.ex$matrix
list.ex[[2]]
list.ex[[4]][,1]
list.ex[[4]][,2]
list.ex[[4]]$altezza
